<template>
  <div class="content">
    <div class="row-bg-query">
      <div><el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="openForm(0)">添加</el-button></div>
      <div>
        <el-date-picker
          v-model="dates"
          type="daterange"
          align="right"
          size="small"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          unlink-panels
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          :picker-options="pickerOptions"
        />
      </div>
      <div><el-input v-model="params.title" size="small" placeholder="请输入文章标题" clearable /></div>
      <div><el-button type="primary" size="small" icon="el-icon-search" @click="search">搜索</el-button></div>
    </div>
    <el-row :gutter="20">
      <el-col v-for="(item, index) in article" :key="index" v-loading="loading" :xs="12" :sm="12" :lg="6" :span="6" class="el-col-acticle">
        <el-card :body-style="{ padding: '0px' }" shadow="hover">
          <el-image class="image" alt="封面图" :src="item.image" @click="openForm(1, item.id)">
            <div slot="error" class="image-slot" style="display: flex; justify-content: center; align-items: center; height: 100%; font-size: 60px; background: #f5f7fa; color: #909399;">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
          <div style="padding: 14px;">
            <div class="acticle-header">
              <span class="title" @click="openForm(1, item.id)">{{ item.title }}</span>
              <span class="createTime">{{ item.createTime }}</span>
            </div>
            <div class="bottom clearfix">
              <time class="time">{{ item.description }}</time>
              <div class="acticle-footer">
                <div class="readNum">
                  <span><svg-icon icon-class="eye-open" /> {{ item.readNum }}</span>
                  <span style="margin-left: 4px;"><svg-icon icon-class="comment" /> {{ item.commentNum }}</span>
                </div>
                <div class="operate-button">
                  <el-button class="button" @click="handleComment(0, item.id)">查看评论</el-button>
                  <el-button type="primary" class="button" @click="openForm(1, item.id)">编辑</el-button>
                  <el-button type="danger" class="button" @click="deleteData(item.id)">删除</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      title="评论信息"
      :visible.sync="commentDialogVisible"
      width="50%"
    >
      <div class="comment">
        <el-input v-model="inputComment" :rows="4" type="textarea" placeholder="写下你的评论" @focus="handleFocus" />
        <transition name="fade">
          <div v-if="postComment" class="comment-footer">
            <el-button type="primary" size="mini" @click="addComment">发布</el-button>
            <el-button size="mini" @click="postComment=false">取消</el-button>
          </div>
        </transition>
      </div>
      <comment
        v-loading="commentLoading"
        :comments="comments.records"
        :is-delete="true"
        height="300px"
        @seeMore="handleSeeMore"
        @turnPage="handleCommentPage"
        @add="handleAdd"
        @delete="handleDelete"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-pagination
      v-if="page.pages"
      background
      layout="prev, pager, next"
      :current-page.sync="params.current"
      :page-size="page.size"
      :page-count="page.pages"
      @current-change="turnPage"
    />
  </div>
</template>

<script>
import comment from '@/components/Comment/index'
import { getArticleList, deleteArticle } from '@/api/article'
import { getCommentList, deleteComment, getSubCommentList, addComment } from '@/api/comment'

export default {
  components: {
    comment
  },
  data() {
    return {
      params: {
        current: 1,
        size: 10
      },
      page: {
        current: 1,
        size: 10
      },
      article: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      dates: '',
      loading: true,
      commentDialogVisible: false,
      commentLoading: false,
      postComment: false,
      commentParams: {
        current: 1,
        size: 10,
        type: 1,
        objectId: 0
      },
      comments: {
        current: 1,
        size: 10,
        total: 0,
        pages: 0,
        records: []
      },
      inputComment: '',
      commentForm: {
        topLevelId: null,
        parentId: null,
        type: 1,
        content: ''
      }
    }
  },
  watch: {
    'page.current': function(newCurrent) {
      this.params.current = newCurrent
    },
    'dates': function(newDates) {
      if (newDates === null) {
        this.params.startDate = null
        this.params.endDate = null
      } else {
        this.params.startDate = newDates[0]
        this.params.endDate = newDates[1]
      }
    },
    'comments.records': function(newComments) {
      this.sortComments(newComments)
    },
    'commentParams.objectId': function(newObjectId) {
      this.commentForm.objectId = newObjectId
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取文章列表
    fetchData() {
      this.loading = true
      getArticleList(this.params).then(response => {
        if (response.code === 200) {
          this.article = response.data.records
          this.page.current = response.data.current
          this.page.size = response.data.current
          this.page.total = response.data.total
          this.page.pages = response.data.pages
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
        this.loading = false
      })
    },
    // 删除文章
    deleteData(id) {
      this.$confirm('是否永久删除该文章?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteArticle(id).then(response => {
          if (response.code === 200) {
            // 删除数组里面的对象，无需再请求
            this.article.forEach(item => {
              if (item.id === id) {
                this.article.splice(this.article.indexOf(item), 1)
                return
              }
            })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message({
              type: 'error',
              message: response.message
            })
          }
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 搜索文章
    search() {
      this.params.title = this.params.title ? this.params.title.trim() : null
      this.fetchData()
    },
    // 翻页
    turnPage() {
      this.fetchData()
    },
    // 打开文章编辑页面
    openForm(type, id) {
      let path = '/article/form'
      if (type === 1) {
        path += '?id=' + id
      }
      this.$router.push(path)
    },
    // 获取输入焦点，显示操作按钮
    handleFocus() {
      this.postComment = true
    },
    // 获取评论
    handleComment(type, id) {
      this.commentDialogVisible = true
      this.commentLoading = true
      if (id !== undefined) {
        this.commentParams.objectId = id
      }
      if (type === 0) {
        this.commentParams.current = 1
      }
      getCommentList(this.commentParams).then(response => {
        if (response.code === 200) {
          if (this.comments.length === 0 || type === 0) {
            this.comments = response.data
          } else {
            response.data.records.forEach(item => {
              this.comments.records.push(item)
            })
          }
          this.comments.current = response.data.current
          this.comments.size = response.data.current
          this.comments.total = response.data.total
          this.comments.pages = response.data.pages
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
        this.commentLoading = false
      })
    },
    // 发布评论
    addComment() {
      if (this.inputComment.trim().length > 0) {
        this.commentForm.parentId = 0
        this.commentForm.content = this.inputComment
        addComment(this.commentForm).then(response => {
          if (response.code === 200) {
            if (response.data) {
              if (this.comments.records.length > 0) {
                this.comments.records.unshift(response.data)
              } else {
                this.handleComment(0, this.commentForm.objectId)
              }
              this.inputComment = ''
            }
          } else {
            this.$message({
              type: 'error',
              message: response.message
            })
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请输入内容',
          duration: 1000
        })
      }
    },
    // 添加评论
    handleAdd(topLevelId, parentId, content) {
      this.commentForm.topLevelId = topLevelId
      this.commentForm.parentId = parentId
      this.commentForm.content = content
      addComment(this.commentForm).then(response => {
        if (response.code === 200) {
          if (response.data) {
            this.comments.records.forEach(item => {
              if (item.id === topLevelId) {
                this.comments.records[this.comments.records.indexOf(item)].children.records.push(response.data)
                return
              }
            })
            this.sortComments(this.comments.records)
          }
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
      })
    },
    // 删除评论
    handleDelete(row) {
      this.$confirm('是否永久删除该留言?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteComment(row.id).then(response => {
          if (response.code === 200) {
            // 删除数组里面的对象，无需再请求
            this.comments.records.forEach(item => {
              if (item.id === row.id) {
                this.comments.records.splice(this.comments.records.indexOf(item), 1)
                return
              }
            })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            this.$message({
              type: 'error',
              message: response.message
            })
          }
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 评论评论翻页
    handleCommentPage() {
      if (this.commentParams.current < this.comments.pages) {
        this.commentParams.current += 1
        this.handleComment()
      }
    },
    // 查看评论更多
    handleSeeMore(id, current) {
      getSubCommentList({ type: 1, current, size: 5, topLevelId: id }).then(response => {
        if (response.code === 200 && response.data.records.length > 0) {
          this.comments.records.forEach(c => {
            if (c.id === id) {
              response.data.records.forEach(item => {
                c.children.records.push(item)
              })
            }
          })
        }
      })
    },
    // 排序评论回复人
    sortComments(comments) {
      if (comments) {
        comments.forEach(item => {
          if (item.children.records !== undefined) {
            item.children.records.forEach(i => {
              item.children.records.forEach(j => {
                if (i.parentId === j.id) {
                  i.upperLevelNickName = j.nickName
                  return
                }
              })
            })
          }
        })
      }
    }
  }
}
</script>

<style>
  .el-range-editor--small .el-range-separator {
    width: 22px;
  }

  .el-picker-panel {
    margin-left: 108px;
  }
</style>

<style lang="scss" scoped>
  .content {
    .comment {
      padding: 0px 10px 16px;
      .comment-footer {
        display: flex;
        justify-content: flex-end;
        margin-top: 6px;
      }
    }
  }

  .el-card {
    box-shadow: 0 2px 12px 0 rgba(0,0,0, 0.1)
  }

	.el-col-acticle {
		padding-top: 2%;
	}

	.el-pagination {
    margin: 1% 0 0 0;
	}

  .acticle-header {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .title:hover {
    cursor: pointer;
    color: red;
  }

  .time {
    font-size: 13px;
    color: #999;
    display: flex;
    height: 86px;
    line-height: 18px;
  }

  .acticle-footer{
    display: flex;
    justify-content: space-between;
    .readNum {
      font-size: 13px;
      color: #999;
      margin-top: 6px;
    }
    .operate-button {
      display: flex;
      justify-content: flex-end
    }
  }

  .createTime {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 4px 10px;
  }

  .image {
    width: 100%;
    height: 240px;
    display: block;
    cursor: pointer;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
      clear: both
  }

  .el-pager li {
    background-color: #fff;
  }
</style>
